<?php
namespace app\api\controller\v1;

use app\api\model\Image as ImageModel;
use app\api\service\TokenService;
use app\api\validate\ImageValidate ;
use app\api\validate\ImagetypeValidate;
use app\lib\exception\ImageException;
use think\helper\Time;

//用户地址类
class Image extends Base
{
    //TP5的前置方法
    protected $beforeActionList = [
        //'checkScope' => ['only' => 'createOrUpdateAddress']
        'checkScope'
    ];

    //上传图片
    public function upload_image(){
        $validate = new ImageValidate();
        $validate->goCheck();
        $uid = TokenService::getCurrentUid();//接收token，获取uid
        $post = $validate->getDataByRule(input('post.'));//过滤非验证器中的字段
        if($this->request->file('file')){
            $file = $this->request->file('file');
        }else{
            $res['code']=402;
            $res['msg']='没有上传文件';
            return json($res);
        }
        $image = ImageException::img_name($post['img_type']);
        $info = $file->validate(['ext'=>'jpg,png'])->rule('date')->move('./uploads/wechat/'.$image);
        if($info) {
            //写入到附件表
            $data = [];
            $data['id'] = $post['id'];
            $data['img'] = '/uploads/wechat/' . $image .'/'. $info->getSaveName();//文件路径
            $data['type'] = $post['type'];
            $data['img_type'] = $post['img_type'];
            $img_small = \think\Image::open('.'.$data['img']);
            $temp = explode('/',$info->getSaveName());
            $thumb = $temp['0'].'/thumb_'.$temp['1'];
            $img_small->thumb(300,180,\think\Image::THUMB_SCALING)->save('./uploads/wechat/'.$image.'/'.$thumb);
            $data['img_small'] = '/uploads/wechat/'.$image.'/'.$thumb;
            return ImageModel::CreateOne($uid,$data);
        } else {
            // 上传失败获取错误信息
            return json($file->getError(),402);
        }
    }

    //获取图片信息
    public function image_info(){
        $validate = new ImageTypeValidate();
        $validate->goCheck();
        $post = $validate->getDataByRule(input('post.'));//过滤非验证器中的字段
        $uid = TokenService::getCurrentUid();//接收token，获取uid
        return ImageModel::GetInfo($uid,$post);
    }

    //删除图片
    public function del_image($type=''){
        $uid=TokenService::getCurrentUid();
        return ImageModel::image_all_del($uid,$type);
    }
}
